package com.chenbei.erp.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chenbei.common.exception.LogicHandleException;
import com.chenbei.erp.domain.Warehouse;
import com.chenbei.erp.vo.req.WarehouseReq;
import com.chenbei.erp.mapper.WarehouseMapper;
import com.chenbei.erp.service.IWarehouseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class WarehouseService extends ServiceImpl<WarehouseMapper, Warehouse> implements IWarehouseService {

    @Override
    public void add(Warehouse warehouse) {
        LambdaQueryWrapper<Warehouse> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Warehouse::getName, warehouse.getName());
        if (count(lambdaQueryWrapper) > 0) {
            throw new LogicHandleException("仓库名称已存在");
        }
        save(warehouse);
    }

    @Override
    public void update(Warehouse warehouse) {
        LambdaQueryWrapper<Warehouse> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Warehouse::getName, warehouse.getName())
                .ne(Warehouse::getId, warehouse.getId());
        if (count(lambdaQueryWrapper) > 0) {
            throw new LogicHandleException("仓库名称已存在");
        }
        updateById(warehouse);
    }

    @Override
    public Page<Warehouse> pageList(WarehouseReq req) {
        Page<Warehouse> pageConfig = new Page<>(req.getPageNum(), req.getPageSize());
        LambdaQueryWrapper<Warehouse> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(Warehouse::getId);
        if (StrUtil.isNotBlank(req.getName())) {
            lambdaQueryWrapper.like(Warehouse::getName, req.getName());
        }
        if (StrUtil.isNotBlank(req.getManagerName())) {
            lambdaQueryWrapper.like(Warehouse::getManagerName, req.getManagerName());
        }
        if (StrUtil.isNotBlank(req.getManagerPhone())) {
            lambdaQueryWrapper.like(Warehouse::getManagerPhone, req.getManagerPhone());
        }
        if (req.getStatus() != null && req.getStatus() >= 0) {
            lambdaQueryWrapper.eq(Warehouse::getStatus, req.getStatus());
        }
        return page(pageConfig, lambdaQueryWrapper);
    }

    @Override
    public void deleteId(Long id) {
        removeById(id);
    }
}
